//获取应用实例
var app = getApp();
var reLoginNum = 0;

// 初始化数据
var init = {

  // 数据
  data: {
    loading:true,
    // 优惠码
    selectCouponSn: '',
    limitPrice:0,
    cutmoney:0,

    //是否使用积分
    usePoints: 0,

    // 是否显示优惠券列表
    showCoupon: false,

    // 订单总金额
    totalAmount: 0,
    daodian:false,
    order_type: '',
    sendFood:false,
    frist:false,
    array: [],
    checked_goods:[],
    api:app.api,
    totalpay:0,//总价+满减+优惠券
    allcut:0,//已优惠
  },

  // 页面第一次加载
  onLoad: function (options) {
    console.log(options);
    var that = this;
    that.setData({
      options: options,
      store_id: options.store_id,
      fromcart: options.fromcart
    })
    // 登录授权
  },
  /**
 * 生命周期函数--监听页面初次渲染完成
 */
  onReady: function () {
    var that = this;
    that.cartData();
    that.setData({
      first:true
    })
    console.log("aefe");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    setTimeout(function () {
      if (that.data.first == true) { 
        console.log("aaa"); 
        that.setData({
          first: false
        })
      }else{
        app.getLoginSession(function (session) {
          that.setData({
            loading:true,
            order_type: '',
            sendFood: false,
            frist: false,
          })
          that.getData(session);
        })
      }
    }, 1000) //延迟时间 这里是1秒  
    
  },
  cartData: function () {
    var that = this;
    var arr= [];
    that.setData({
      goodsnum: 0
    })
    app.getLoginSession(function (session) {
      wx.request({
        url: app.api,
        data: {
          app: 'cart',
          t_session: session,
          store_id: that.data.store_id
        },
        success: function (res) {
          var data = res.data;
          if (data.done && data.retval) {
            if (data.retval.goods != null) {
              that.setData({
                cartlist: data.retval.goods
              })
              for(var i = 0 ;i<data.retval.goods.length;i++){
                arr.push(data.retval.goods[i].goods_id + '_' + data.retval.goods[i].spec_id + '_' + data.retval.goods[i].quantity);
                that.setData({
                  checked_goods:arr
                })
              }
              app.getLoginSession(function (session) {
                that.getData(session);
              })
            }
          }
        }
      })
    })
  },
  // 获取数据
  getData: function (session) {

    var that = this;
    var options = that.data.options;
    var params = {
      app: 'order',
      goods: 'cart',
      checked_goods: that.data.checked_goods.join(),
      fromcart: 1,
      t_session: session,
      store_id: that.data.store_id
    }

    console.log(params);

    // 创建来源页面参数，让选择地址后可以返回
    var referer = '';
    for (var i in params) {
      referer += '&' + i + '=' + params[i]
    }

    // 请求前
    that.setData({

      // 来源参数
      referer: '?' + referer.substr(1) + '&from=' + 'confirmOrder' + (options.formCart ? '&fromCart=' + options.fromCart : ''),

      // 开启loading
      loading: true
    });

    console.log(that.data.referer);

    // 请求
    wx.request({

      // 请求地址
      url: app.api,

      // 请求参数
      data: params,

      // 请求成功
      success: function (res) {
        var data = res.data;
        console.log(data.retval);
        if (data.done) {

          that.setData({
            data: data.retval,
            array:that.table(data.retval.goods_info.position),

            // 保存订单原始总价
            totalAmount: parseFloat(data.retval.goods_info.amount),
            totalpay: parseFloat(data.retval.goods_info.amount),

            // 关闭loading效果
            loading: false
          })
          console.log(that.data.array);
          that.data.data.goods_info.store.distribution_fee = parseFloat(that.data.data.goods_info.store.distribution_fee);
          that.setData({
            data:that.data.data
          })
          //获取购物车列表
          wx.request({
            url: app.api,
            data: {
              app: 'store',
              act: 'get_detail',
              store_id: that.data.store_id
            },
            success: function (res) {
              var data = res.data;
              if (data.done && data.retval) {
                console.log(res);
                that.setData({
                  sale: app.turn(data.retval.sale_promotion),
                  store:data.retval.store
                })
                if (that.data.sale.length>0){
                  var limit = that.data.sale[0].limit_price;
                  for(var i = 0;i<that.data.sale.length;i++){
                    console.log(i);
                    if (that.data.totalAmount >= that.data.sale[i].limit_price) {
                      if (limit <= that.data.sale[i].limit_price) {//因为满减优惠的顺序问题，所以我们要判断当前的满价格是否大于上一个的满价格，则重新赋值
                      console.log(that.data.sale[i].limit_price);
                        limit = that.data.sale[i].limit_price;
                        that.setData({
                          cutmoney: parseFloat(that.data.sale[i].sale_value),
                          allcut: parseFloat(that.data.sale[i].sale_value),
                          totalpay: (parseFloat(that.data.totalpay) - parseFloat(that.data.sale[i].sale_value)).toFixed(2),
                          totalpay_c: (parseFloat(that.data.totalpay) - parseFloat(that.data.sale[i].sale_value)).toFixed(2)
                        })
                      }
                    }
                    
                  }
                }
              } else {
                that.setData({
                  loading: false,
                  loadTips: '暂无相关信息'
                })
              }
            },
            fail: function () {
              that.setData({
                loading: false,
                loadTips: '接口连接错误'
              })
            }
          })
          console.log(res);

        } else {

          // 检查是否登录失败
          if (data.reLogin && (reLoginNum <= app.reLoginNum)) {
            app.login(function (session) {
              that.getData(that.data.options, session);
            });
            reLoginNum++;
          } else {
            that.setData({
              errorTips: data.msg || '请求错误，act：buynow'
            })
          }
        }

      },

      // 请求失败
      fail: function () {
        that.setData({
          errorTips: '接口请求失败，act：buynow'
        })
      }
    });

  },

  // 使用积分
  usePoints: function () {
    var that = this;
    that.setData({
      usePoints: that.data.usePoints == 0 ? 1 : 0,
      'data.goods_info.amount': (function () {
        if (that.data.usePoints == 0) {
          var newAmount = (parseFloat(that.data.totalAmount) - parseFloat(that.data.data.integral_money)).toFixed(2);
          return newAmount > 0 ? newAmount : 0
        } else {
          return that.data.totalAmount
        }
      })()
    });

  },

  // 显示优惠券列表
  showCoupon: function () {
    var that = this;
    that.setData({
      showCoupon: !that.data.showCoupon
    })
  },

  // 选择优惠券
  selectCouponSn: function (event) {
    console.log(event.currentTarget.dataset.sn);
    var that = this;
    var sn = event.currentTarget.dataset.sn;
    var price = event.currentTarget.dataset.price;
    that.setData({
      selectCouponSn: sn,
      showCoupon: !that.data.showCoupon,
      limitPrice: parseFloat(price),
      totalpay_c: (parseFloat(that.data.totalAmount) - parseFloat(that.data.cutmoney) - parseFloat(price) + parseFloat(that.data.data.goods_info.store.distribution_fee)).toFixed(2),
      totalpay: (parseFloat(that.data.totalAmount) - parseFloat(that.data.cutmoney) - parseFloat(price)).toFixed(2),
      allcut:(parseFloat(price)+parseFloat(that.data.cutmoney)).toFixed(2),
      // 'data.goods_info.amount': (parseFloat(that.data.totalAmount) - parseFloat(price)).toFixed(2)
    })
  },

  // 添加留言
  msg: function (event) {
    this.setData({
      msg: event.detail.value
    })
  },

  // 确认提交
  submit: function () {
    var that = this;
    var options = that.data.options;
    var data = that.data.data;
    if (that.data.daodian == false && that.data.sendFood==false){
      wx.showModal({
        title: '温馨提示',
        content: '请选择就餐方式！'
      })
      return false;
    }
    if (that.data.order_type==1&&that.data.data.addresses.length==0){
      wx.showModal({
        title: '温馨提示',
        content: '请添加收货地址'
      })
      return false;
    }
    if (that.data.order_type == 1 && that.data.data.addresses[0].carry == 0) {
      wx.showModal({
        title: '警告',
        content: '您的地址不在配送范围内！'
      })
      return false;
    }
    if (that.data.order_type == 1 && that.data.options.charging_fee >= that.data.totalAmount) {
      wx.showModal({
        title: '温馨提示',
        content: '本店满' + that.data.options.charging_fee+'起送'
      })
      return false;
    }
    if (that.data.order_type == 0 && that.data.table_index==undefined){
      wx.showModal({
        title: '温馨提示',
        content: '请选择座位号，谢谢。'
      })
      return false;
    }
    // if(that.data.daodian==true){
    //   wx.navigateTo({
    //     url: '/pages/paySuccess/paySuccess',
    //   })
    // }else{
    //   wx.navigateTo({
    //     url: '/pages/orderDetail/orderDetail',
    //   })
    // }
    app.getLoginSession(function (session) {

      var params = {};
      var api = app.api;
          var checkedGoods = [];
          for (var i = 0; i < data.goods_info.goods.length; i++) {
            checkedGoods.push(data.goods_info.goods[i].goods_id + '_' + data.goods_info.goods[i].spec_id)
          }

          params = {
            app: 'order',
            goods: 'cart',
            checked_goods: that.data.checked_goods.join(),
            mall_coupon: that.data.selectCouponSn,
            use_integral: that.data.usePoints,
            my_address: data.addresses.length==0?'0101001':data.addresses[0].addr_id,
            order_token: data.order_token,
            message: that.data.msg || '',
            order_type: that.data.order_type,
            seat_number: that.data.order_type==0?that.data.array[that.data.table_index]:'',
            store_id:that.data.store_id,
            t_session: session
          }

        // 生成订单号
        wx.showLoading({
          title: '确认中...'
        });

        // 请求
        wx.request({

          // 请求地址
          url: api,

          // 请求参数
          data: params,

          // 请求头
          header: {
            "Content-Type": "application/x-www-form-urlencoded"
          },

          // 请求方法（后端根据method来判断是提交还是确认）
          method: 'POST',

          // 请求成功
          success: function (res) {
            console.log(res.data);
            var data = res.data;
            var amount = that.data.data.goods_info.amount; // 金额大于0才能支付
            app.callToPay(data.retval.order_id, amount, that.data.store_id);
            wx.hideLoading();
          }
        })
      

    })
  },
  daodian_cb:function(){
    var that = this;
    that.setData({
      totalpay: (parseFloat(that.data.totalAmount) - parseFloat(that.data.cutmoney) - parseFloat(that.data.limitPrice)).toFixed(2),
      totalpay_c: (parseFloat(that.data.totalAmount) - parseFloat(that.data.cutmoney) - parseFloat(that.data.limitPrice)).toFixed(2)
    })
    if (that.data.sendFood == true) {
      that.setData({
        sendFood: false,
        order_type: 0
      })
    }
    that.setData({
      daodian:that.data.daodian==true?false:true
    })
    if (that.data.daodian==true){
      wx.showModal({
        title: '温馨提示',
        content: '自取快餐/到店消费，下单成功后，店家立即为您备餐，请耐心等待。(下单成功后不允许取消订单、退款，不便之处请多见谅。)',
        success: function (res) {
          if (res.confirm) {
            console.log("aaa");
            that.setData({
              order_type:0
            })
          } else if (res.cancel) {
            that.setData({
              daodian:false,
              order_type: ''
            })
          }
        }  
      })
    }
  },
  sendFood_cb: function () {
    var that = this;
    if (that.data.daodian == true) {
      that.setData({
        daodian: false,
        order_type:1,
      })
    }
    that.setData({
      sendFood: that.data.sendFood == true ? false : true
    })
    if(that.data.sendFood==false){
      that.setData({
        order_type:'',
        totalpay: (parseFloat(that.data.totalAmount) - parseFloat(that.data.cutmoney) - parseFloat(that.data.limitPrice)).toFixed(2),
        totalpay_c: (parseFloat(that.data.totalAmount) - parseFloat(that.data.cutmoney) - parseFloat(that.data.limitPrice)).toFixed(2)
      })
    }else{
      that.setData({
        order_type: 1,
        totalpay: (parseFloat(that.data.totalAmount) - parseFloat(that.data.cutmoney) - parseFloat(that.data.limitPrice) + parseFloat(that.data.data.goods_info.store.distribution_fee)).toFixed(2),
        totalpay_c: (parseFloat(that.data.totalAmount) - parseFloat(that.data.cutmoney) - parseFloat(that.data.limitPrice) + parseFloat(that.data.data.goods_info.store.distribution_fee)).toFixed(2)
      })
    }
  },
  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      table_index: e.detail.value
    })
  },
  // 显示所有菜单
  show_all: function () {
    var that = this;
    that.setData({
      showall: that.data.showall == true ? false : true
    })
  },
  //遍历座位号
  table:function(res){
    var arr=[];
    var length=res.end_number-res.start_number+1;
    for(var j = res.start_number;j<=res.end_number;j++){
      arr.push(parseInt(j));
    }
    res=arr;
    return res;
  }

};

// 注册页面
Page(init);
